package com.anji.plus.gaea.push.type.dingding.template;

import com.anji.plus.gaea.push.type.param.PushParamVO;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiUserGetByMobileRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiUserGetByMobileResponse;
import com.taobao.api.ApiException;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;

/**
 * @ClassName DingDingOperations
 * @Description: TODO
 * @Author dingkaiqiang
 * @Date 2021-04-07
 * @Version V1.0
 **/
public abstract class DingDingOperations {


    /**
     * 根据批量手机号查询用户id
     * 需要注意ip不在白名单
     * @return
     */
    public String getUserInfoByMobleBatch(String mobileStr) {
        List<String> mobiles = Arrays.asList(mobileStr.split(","));
        if (CollectionUtils.isEmpty(mobiles)) {
            return "";
        }
        DingTalkClient client = new DefaultDingTalkClient(DingDingTemplate.GET_BY_MOBILE);
        OapiUserGetByMobileRequest request = new OapiUserGetByMobileRequest();
        StringBuilder userIds = new StringBuilder();
        mobiles.stream().forEach(mobile ->{
            request.setMobile(mobile);
            try {
                OapiUserGetByMobileResponse execute = client.execute(request, getAccessToken());
                userIds.append(execute.getUserid()).append(",");
            } catch (ApiException e) {
                e.printStackTrace();
            }

        });

        System.out.println("userId:=====  " +userIds.toString());
        return userIds.toString();

    }

    /**
     * 获取accessToken
     * @return
     */
    public String getAccessToken() {
        DefaultDingTalkClient client = new DefaultDingTalkClient(DingDingTemplate.TOKEN_URL);
        OapiGettokenRequest request = new OapiGettokenRequest();
        request.setAppkey(DingDingTemplate.APPKEY);
        request.setAppsecret(DingDingTemplate.APPSECRET);
        request.setHttpMethod("GET");
        try {
            OapiGettokenResponse response = client.execute(request);
            System.out.println(response);
            return response.getAccessToken();

        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }
}
